package jing.upnp.ssdp.type.usn;

import android.util.Log;

/**
 * Created by ouyang on 15-9-10.
 */
public class UsnFactory {

    private static final String TAG = "UsnFactory";

    private UsnFactory() {
    }

    public static Usn create(String string) {
        Usn usn = new Usn();

        do {
            String[] a = string.split("::");
            if (a.length == 0) {
                Log.d(TAG, "length is 0: " + string);
                usn = null;
                break;
            }

            usn.setDeviceUuid(getUuidWithoutPrefixIgnoreCase("uuid:", a[0]));
            if (usn.getDeviceUuid() == null) {
                Log.d(TAG, "uuid is invalid: " + a[0]);
                usn = null;
                break;
            }

            if (a.length != 2) {
                break;
            }

            usn.setUri(UriFactory.createWithString(a[1]));
            if (usn.getUri() == null) {
                Log.d(TAG, "uri is invalid: " + a[1]);
                usn = null;
                break;
            }
        } while (false);

        return usn;
    }

    public static Usn createWith(String deviceUuid) {
        Usn usn = null;

        do {
            if (deviceUuid == null) {
                break;
            }

            usn = new Usn();
            usn.setDeviceUuid(deviceUuid);
        } while (false);

        return usn;
    }

    public static Usn createWith(String deviceUUID, Uri uri) {
        Usn usn = null;

        do {
            if (deviceUUID == null) {
                break;
            }

            if (uri.getType() == Uri.Type.DeviceUUID) {
                break;
            }

            usn = new Usn();
            usn.setDeviceUuid(deviceUUID);
            usn.setUri(uri);
        } while (false);

        return usn;
    }

    private static String getUuidWithoutPrefixIgnoreCase(String prefix, String fullUuid) {
        String uuid = null;

        String u = fullUuid.toLowerCase();
        String p = prefix.toLowerCase();

        if (u.startsWith(p)) {
            uuid = u.substring(p.length());
        }

        return uuid;
    }
}